package com.minyifang.wcspf.work.service;

import android.app.DownloadManager;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.database.Cursor;
import android.net.Uri;
import android.os.Environment;

import com.minyifang.wcspf.common.utils.LogUtil;
import com.minyifang.wcspf.common.utils.SPUtils;

import java.io.File;
import java.lang.ref.WeakReference;

/**
 * Created by LuoYaWei on 2018/7/10.
 */
public class DownLoadHelper {

    private static long downloadId;
    private static DownloadManager manager;
    private static boolean isVisiable;
    private static int type;
    private static WeakReference<Context> weakReference;

    /**
     * @param context    上下文对象
     * @param url        下载链接
     * @param isVisiable 是否在通知栏显示
     * @param type       类型 0: 图片 1: 视频
     */
    public static void downLoad(Context context, String url, boolean isVisiable, int type) {

        DownLoadHelper.weakReference = new WeakReference<>(context);
        DownLoadHelper.isVisiable = isVisiable;
        DownLoadHelper.type = type;

        String fileName = url.substring(url.lastIndexOf("/") + 1);
        LogUtil.e("根据url获取的文件名: " + fileName);
        manager = (DownloadManager) context.getSystemService(Context.DOWNLOAD_SERVICE);
        // 创建下载请求
        DownloadManager.Request request = new DownloadManager.Request(Uri.parse(url));
        /*
         * 设置在通知栏是否显示下载通知(下载进度), 有 3 个值可选:
         *    VISIBILITY_VISIBLE:                   下载过程中可见, 下载完后自动消失 (默认)
         *    VISIBILITY_VISIBLE_NOTIFY_COMPLETED:  下载过程中和下载完成后均可见
         *    VISIBILITY_HIDDEN:                    始终不显示通知
         */
        request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE);
        // 设置通知的标题和描述
        request.setTitle("开始下载");
        request.setDescription("开始下载");

        // 添加请求头
        // request.addRequestHeader("User-Agent", "Chrome Mozilla/5.0");

        // 设置下载文件的保存位置
        File saveFile = new File(Environment.getExternalStorageDirectory(), fileName);
        request.setDestinationUri(Uri.fromFile(saveFile));

        downloadId = manager.enqueue(request);

        //注册广播接收者，监听下载状态
        context.registerReceiver(receiver,
                new IntentFilter(DownloadManager.ACTION_DOWNLOAD_COMPLETE));
    }


    //广播监听下载的各个状态
    private static BroadcastReceiver receiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            checkStatus();
        }
    };

    private static void checkStatus() {
        DownloadManager.Query query = new DownloadManager.Query();
        //通过下载的id查找
        query.setFilterById(downloadId);
        Cursor c = manager.query(query);
        if (c.moveToFirst()) {
            int status = c.getInt(c.getColumnIndex(DownloadManager.COLUMN_STATUS));
            switch (status) {
                //下载暂停
                case DownloadManager.STATUS_PAUSED:
                    break;
                //下载延迟
                case DownloadManager.STATUS_PENDING:
                    break;
                //正在下载
                case DownloadManager.STATUS_RUNNING:
                    break;
                //下载完成
                case DownloadManager.STATUS_SUCCESSFUL:
                    if (isVisiable) {
                        //apk 跳转到安装
                        //installAPK();
                    } else {
                        Context context = weakReference.get();
                        if (context == null) return;
                        //下载图片视频等
                        // 下载文件在本地保存的路径（Android 7.0 以后 COLUMN_LOCAL_FILENAME 字段被弃用, 需要用 COLUMN_LOCAL_URI 字段来获取本地文件路径的 Uri）
                        String localFilename = c.getString(c.getColumnIndex(DownloadManager.COLUMN_LOCAL_URI));
                        SPUtils.put(context, "splash_type", type);
                        SPUtils.put(context, "splash_path", localFilename);
                        LogUtil.e("下载成功 --" + localFilename);
                    }
                    break;
                //下载失败
                case DownloadManager.STATUS_FAILED:
                    LogUtil.e("下载失败");
                    break;
            }
        }
        c.close();

    }

    public static void unregisterReceiver() {
        if (weakReference == null) return;
        Context context = weakReference.get();
        if (context == null) return;
        context.unregisterReceiver(receiver);

    }

    public static void start() {

    }
}
